<?php
	include_once "notesrack.php";

	if ( isset( $_GET['login_form'] ) and ( count( $_GET ) == 1 ) and isset($_SERVER['HTTP_REFERER']) ) {
		get_login_form();
	}
	
	if ( isset( $_GET['register_form'] ) and ( count( $_GET ) == 1 ) and isset($_SERVER['HTTP_REFERER']) ) {
		get_register_user_form();
	}
	
	if ( isset( $_GET['passwordreset_form'] ) and ( count( $_GET ) == 1 ) and isset( $_SERVER['HTTP_REFERER'] ) ) {
		get_passwordreset_form();
	}	
	
	if ( isset($_GET['login']) and count( $_GET == 1 ) ) {
		$response = array();
		if ( ! empty ($_POST['username'] ) and ! empty ( $_POST['password'] ) ) {
			$response = check_login( $_POST['username'], $_POST['password'] );
			# response carries an array with errors, and success messages.
			# the javascript will take it forward.
			echo json_encode( $response );
			exit;
		} else {
			$response["errors"] = "<div>You must provide a valid user name and password.</div>";
			echo json_encode($response);
			exit;
		}
	}	
	
	if ( isset( $_GET['register'] ) and count( $_GET == 1 ) ) {
		json_return_debug_output( "register user.." );		
		$response = array();
		if ( ! empty ($_POST['username'] ) and ! empty ( $_POST['password'] ) and ! empty( $_POST['email'] ) ) {		
				$response = register_user ( $_POST['username'], $_POST['password'],  $_POST['email'] );
				echo json_encode( $response );
				exit;
		} else {
			$response["errors"] = "<div>You must provide a valid user name, password, and email address.</div>";
			echo json_encode($response);
		}
	}
	
	if ( isset( $_GET['password_reset'] ) and count( $_GET == 1 ) ) {
		$response = array();
		if ( ! empty ($_POST['username'] ) and ! empty ( $_POST['old_password'] ) and ! empty( $_POST['new_password'] ) ) {		
				$response = password_reset ( $_POST['username'], $_POST['old_password'],  $_POST['new_password'] );
				echo json_encode( $response );
				session_destroy(); // We want the user to login afresh.
				exit;
		} else {
			$response["errors"] = "<div>You must provide valid user name, and old and new passwords.</div>";
			echo json_encode($response);
			session_destroy(); // We want the user to login afresh.
		}
	}
	
	if ( isset( $_GET['logout'] ) and count( $_GET == 1 ) ) {
		session_destroy();
		header( sprintf("Location:%s", get_url_to("notes.php")) );
		exit;
	}	
	
?>